<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部警告条区域 -->
      <el-alert title="添加商品" type="info" center show-icon :closable="false">
      </el-alert>

      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab导航栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs v-model="activeIndex" tab-position="left"  :before-leave='beforeTabLeave' @tab-click='handleTabClick'>
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                clearable
                :options="catelist"
                :props="{
                  expandTrigger: 'hover',
                  value: 'cat_id',
                  label: 'cat_name',
                  checkStrictly: true
                }"
                @change="handleCascaderChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="(item) in manyTabData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals" size="small">
              <el-checkbox :label="subItem" border v-for="(subItem, index) in item.attr_vals" :key="index"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item) in onlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action  图片要上传的api地址 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers='headersObj'
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce">
            </quill-editor>
            <el-button type='primary' class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="30%">
     <img :src="previewUrl" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>
<script>
// 深拷贝
import _ from 'lodash'
export default {
  data () {
    return {
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [1, 3, 6],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      catelist: [],
      // 动态参数的数据
      manyTabData: [],
      // 静态属性的数据
      onlyTabData: [],
      fileList: [],
      // 上传图片设置的请求头
      headersObj: {
        Authorization: sessionStorage.getItem('token')
      },
      previewUrl: '',
      previewVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.catelist = res.data
    },
    // 级联选择框的函数
    handleCascaderChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        return false
      }
      return true
    },
    async handleTabClick () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', {
          params: {
            sel: 'many'
          }
        })
        res.data.forEach(t => {
          t.attr_vals = t.attr_vals.split(',')
        })
        this.manyTabData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', {
          params: {
            sel: 'only'
          }
        })
        this.onlyTabData = res.data
      };
    },
    // 处理图片预览的函数
    handlePreview (file) {
      this.previewUrl = file.response.data.url
      this.previewVisible = true
    },
    // 处理图片移除的函数
    handleRemove (file) {
      // console.log(file)
      const tmpPath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(t => t.pic === tmpPath)
      this.addForm.pics.splice(i, 1)
    },
    // 文件上传成功的函数
    handleSuccess (res) {
      this.addForm.pics.push({ pics: res.data.tmp_path })
    },
    // 点击提交按钮
    add () {
      this.$refs.addForm.validate(async vald => {
        if (vald) {
          // 深拷贝
          const form = _.cloneDeep(this.addForm)
          form.goods_cat = form.goods_cat.join(',')
          this.manyTabData.forEach(t => {
            this.addForm.attrs.push({
              attr_id: t.attr_id,
              attr_value: t.attr_vals.join(',')
            })
          })
          this.onlyTabData.forEach(t => {
            this.addForm.attrs.push({
              attr_id: t.attr_id,
              attr_value: t.attr_vals
            })
          })
          form.attrs = this.addForm.attrs
          // 验证通过
          const { data: res } = await this.$http.post('goods', form)
          if (res.meta.status !== 201) {
            return this.$message.error('添加用户失败')
          }
          this.$message.success('添加商品成功')
          this.$router.push('/goods')
        } else {
          // 验证不通过
          this.$message({
            message: '表单存在错误',
            type: 'error',
            showClose: true,
            duration: 3000
          })
        }
      })
    }
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat[2]
    }
  }
}
</script>
<style lang="less" scope>
.el-steps {
  margin: 15px 0;
  display: flex;
  justify-content: center;
}
.el-step__title {
  font-size: 14px;
}
.el-checkbox {
  margin: 0 10px 0 0!important;
}
.btnAdd {
  margin-top: 10px !important;
}
</style>
